<?php
namespace Common\Models;
use Common\BaseModel;
use Common\Common;

class Order extends BaseModel
{
    public $res;
    public $redis_key = "";

    public function initialize()
    {
        parent::initialize();
        $this->setSource('order');
    }


    //通过订单号，返回订单数组
    public function get_status_by_ids($order_ids, $site)
    {
        $condition = ['conditions' => "order_id in($order_ids) and site='{$site}'", 'columns' => 'order_id,order_status'];
        $res       = $this->find($condition);
        $arr       = [];
        if ($res->toarray() != []) {
            foreach ($res->toarray() as $k => $v) {
                $arr[$v['order_id']] = $v['order_status'];
            }
            return $arr;

        }
        return null;

    }

    //通过订单号，返回订单数组淘宝/饿了么 专用
    public function get_status_by_tb($order_ids, $site)
    {
        $condition = ['conditions' => "order_id in($order_ids) and site in ($site)", 'columns' => 'order_id,order_status'];
        $res       = $this->find($condition);
        $arr       = [];
        if ($res->toarray() != []) {
            foreach ($res->toarray() as $k => $v) {
                $arr[$v['order_id']] = $v['order_status'];
            }
            return $arr;

        }
        return null;

    }
    /**
     * 添加订单每日任务5次加金币
     * @param $user_id
     * @return bool
     */
    public function get_day_task_gold($user_id)
    {
        $start_end_time          = CommonController::timeChange(1);  //今日的收益
        $condition['conditions'] = "user_id = $user_id and order_create_time >= '{$start_end_time['start_at']}' and order_create_time <= '{$start_end_time['end_at']}' and pay_money >= 20 and commition > 0";
        $condition['columns']    = 'count(id) as count';
        $order                   = $this->findFirst($condition);
        if ($order) {
            if ($order->count < 6) {
                return true;
            }
        }
        return false;
    }

    //创建订单
    public function create_update_order($order_list, $is_create = 1)
    {
        foreach ($order_list as $k => $v) {
            if ($is_create) {
                $res = new Order();
            } else {
                //更新佣金
                $condition                 = ['conditions' => "order_id = '{$v['order_id']}'"];
                $res                       = $this->findFirst($condition);
                $res->is_calculation_money = 0;
            }
            foreach ($v as $k1 => $v1) {
                $res->$k1 = $v1;
            }
            $res->in_db_time = time();
            $res->save();
        }
    }

    //获取没有计算的有佣金的订单
    public function get_not_subsidy_commition()
    {
        $condition = ['conditions' => "is_calculation_money = 0 and commition > 0", 'limit' => 500];
        $res       = $this->find($condition);
        return $res;

    }

    //获取没有计算的订单
    public function get_not_subsidy()
    {
        $condition = ['conditions' => "is_calculation_money = 0", 'limit' => 500];
        $res       = $this->find($condition);
        return $res;
    }

    //尝试获取面单订单
    public function get_free_order($user_id = null, $goods_id = null, $order_id = null)
    {
        $condition['conditions'] = "user_id = $user_id and goods_id='$goods_id'";
        if ($order_id) {
            $condition['conditions'] = "order_id='$order_id'";
        }
        $condition['columns'] = 'order_status,commition,order_id,user_id,order_create_time,order_paid_time,order_earning_time,site';
        $res                  = $this->findFirst($condition);
        if ($res != false) {
            return $res->toArray();
        }
        return [];
    }

    //通过tbrid获取订单
    public function is_tbrid($rid)
    {
        $condition['conditions'] = "rid = '{$rid}' and order_status = 6";
        $condition['columns']    = 'count(id) as c ';
        $res                     = $this->findFirst($condition);
        if ($res != false) {
            if (intval($res->c) > 1) {
                return true;
            }
        }
        return false;

    }

    public function get_order_by_order_id($order_id)
    {
        $condition['conditions'] = "order_id = '$order_id'";
        $res                     = $this->findFirst($condition);
        if ($res != false) {
            $res = $res->toArray();
        }
        return $res;
    }

    /**
     *  获取冻结金币
     * @param $user_id
     * @return array
     */
    public function get_order_by_user($user_id, $begin_time, $end_time, $is_page = 0, $page = 1, $size = 10)
    {
        $limit_time              = '2020-04-20 00:00:00';
        $yuanbao                 = new YuanBao();
        $yuanbaoData             = $yuanbao->findFirstByid(1);

        $condition['conditions'] = "user_id = {$user_id['id']} and order_create_time >= '$limit_time' and order_create_time >= '$begin_time' and order_create_time <= '$end_time' and is_gold = 0 and order_status in (2,4,6) and commition > 0";
        $condition['order']      = 'order_create_time desc';
        if ($is_page == 0) {
            if ($page > 0) {
                $page = ($page - 1) * $size;
            }
            $condition['limit']  = $size;
            $condition['offset'] = $page;
        }

        $res  = $this->find($condition);

        $data = array();
        if ($res != false) {
            $newData = array();
            foreach ($res as $tval) {

                $newData[$tval->order_id] = $tval->toArray();
            }
            $lv = $this->get_extra_gold($user_id['direct_vip'], $user_id['level_id']);
            foreach ($newData as $val) {
                $temp['gold']               = intval($val['commition'] * $lv * $yuanbaoData->gold_ratio);
                $temp['order_create_time']  = $val['order_create_time'];
                $temp['order_earning_time'] = $val['order_create_time'];
                $temp['goods_name']         = $val['goods_name'];
                $temp['is_day_task_gold']   = $val['is_day_task_gold'] ? true : false;
                if ($temp['is_day_task_gold']) {
                    $temp['day_task_gold'] = '100';
                } else {
                    $temp['day_task_gold'] = '0';
                }
                $data[] = $temp;
            }
        }

        return $data;
    }

    /**
     * 运营商额外赠送金币比例
     * @param $num
     * @return float|int
     */
    public function get_extra_gold($num, $level)
    {
        $lv = 1;
        if ($level == 1) {
            $lv += $num * 0.8 > 4 ? 4 : $num * 0.8;
        }
        return round($lv / 100, 3);
    }

    /**
     * 每日订单数
     * @param $user_id
     * @return mixed
     */
    public function get_day_shopping()
    {
        $beg        = date('Y-m-d 00:00:00');
        $end        = date('Y-m-d 23:59:59');
        $conditions = " order_create_time >= ?1 and order_create_time <= ?2 and pay_money >= ?3";
        $parameters = array(1 => $beg, 2 => $end, 3 => 20);

        $count_array = $this:: find(array(
            $conditions,
            "columns" => "id",
            "bind"    => $parameters
        ));

        if ($count_array) {
            $newData = array();
            foreach ($count_array->toArray() as $val) {
                $newData[$val['user_id']][] = $val;
            }

            return $newData;
        }

        return array();
    }

    /**
     * 每日成长值
     * @param $user_id
     * @return mixed
     */
    public function get_day_growth_val()
    {
        $beg        = date('Y-m-d 00:00:00');
        $end        = date('Y-m-d 23:59:59');
        $conditions = " order_create_time >= ?1 and order_create_time <= ?2 and is_growth_val = 0 and order_status in (2,4,6)";
        $parameters = array(1 => $beg, 2 => $end);

        $count_array = $this:: find(array(
            $conditions,
            "columns" => "user_id",
            "bind"    => $parameters
        ));
        if ($count_array) {
            $newData = array();
            foreach ($count_array as $val) {
                $newData[$val->user_id][] = $val->user_id;
//                $val->is_growth_val = 1;
//                $val->save();
            }
            return $newData;
        }

        return array();
    }

    //最近下单时间
    public function get_last_order_time($user_id)
    {
        $conditions = "user_id = $user_id";

        $count_array = $this:: findFirst(array(
            $conditions,
            "columns" => "order_create_time",
            "order"   => "id desc",
        ));

        if ($count_array) {
            return $count_array->order_create_time;
        } else {
            return false;
        }
    }


    /**
     * 自己购买的总和和节省的总和
     * @param $user_id 用户id
     * @param $field 获取字段总和
     */
    public function buyusermoney($user_id, $field = 'price', $data = [])
    {
        $conditions = "user_id={$user_id}";
        if (isset($data['order_status'])) {
            $conditions .= " AND order_status in({$data['order_status']})";
        } else {
            $conditions .= " AND order_status in(4,6)";
        }
        $money_array = $this:: SUM(array(
            $conditions,
            "column" => $field,
        ));
        return $money_array;
    }

    //批量修改
    public function batch_update($id)
    {
        $updateSql = <<<ENT
UPDATE `w_union_order`
    SET is_gold = 1
WHERE id IN ($id)
ENT;
        return $this->getDI()->get('db')->execute($updateSql);
    }



    /**
     * 分佣
     */
    public function calculate_commission($v)
    {
        $user = new User();
        $userInfo = $user->find_by_id($v->user_id);
        if (!$userInfo) {
            return '用户ID错误';
        }
        if ($userInfo->is_buyed == 0) {
            $userInfo->is_buyed = 1;
            $user               = new User();
            $reInfo             = $user->find_by_id($userInfo->referer_id);
            $reInfo->save();
            $userInfo->save();
        }
        //计算佣金 区域佣金
        //$money_info = $user->CalculatingMoneyV2($v->user_id, $v->commition, $v->pay_money, $v->is_virtual,$v->site);
        $money_info = Common::self_CalculatingMoney($v->user_id, $v->commition, $v->pay_money);
        if ($money_info['commition']) {
            $OrderCommissions = new OrderCommissions();
            $OrderCommissions->add_commissions($v->toArray(), $money_info['commition']);
            $v->is_calculation_money = 1;
        } else {
            $v->is_calculation_money = -1;
            $v->remark               = $money_info['msg'];
        }
        $v->save();
        return true;
    }





}
